package mat;

import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

public class TextMatrixReader extends FileParser implements IFileParser
{
	private Logger log;
	private List<double[]> rows = new LinkedList<double[]>();
	private int lastColCnt = -1;
	private Mat matrix;
	private String name;

	public TextMatrixReader(String name, String fileName)
	{
		super(fileName, null);
		cb = this;
		this.name = name;
		this.log = Logger.getLogger(this.getClass());			
	}
	
	


	public Mat getMatrix()
	{
		return matrix;
	}
	
	


	@Override
	public void process() throws FileParserException
	{
		super.process();
		
		double[][] matrix = new double[rows.size()][lastColCnt];
		for (int i = 0; i < matrix.length; i++)
		{
			for (int j = 0; j < lastColCnt; j++)
			{
				matrix[i][j] = rows.get(i)[j];
			}
		}
		
		this.matrix = new Mat(this.name, matrix);
	}




	@Override
	public void OnParseFileRow(String row)
	{
		String[] parts = row.trim().split("[ ]|;|,");
		
		if (lastColCnt < 0)
			lastColCnt = parts.length;
		else
		{
			if (lastColCnt != parts.length)
			{
				log.error("# of cols should be " + lastColCnt + ": " + row);
				return;
			}
			
			lastColCnt = parts.length;
			
		}
		
		double[] rowValues = new double[parts.length];

		for (int i = 0; i < rowValues.length; i++)
			rowValues[i] = Double.parseDouble(parts[i]);
		
		rows.add(rowValues);		
	}

}


